package com.example.sse.controller;

import com.example.sse.service.SseConnectionManager;
import com.example.sse.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 监控控制器
 * 提供监控相关的API接口
 */
@Slf4j
@RestController
@RequestMapping("/api/monitor")
@RequiredArgsConstructor
public class MonitorController {

    private final SseConnectionManager sseConnectionManager;

    /**
     * 获取监控指标
     * @return 监控指标数据
     */
    @GetMapping("/metrics")
    public ResponseEntity<Map<String, Object>> getMetrics() {
        Map<String, Object> metrics = MapUtils.of(
            "activeConnections", sseConnectionManager.getActiveConnectionCount(),
            "totalMessages", 0, // 可以添加消息计数器
            "clusterNodes", 1, // 简化的集群节点数
            "nodeId", sseConnectionManager.getNodeId(),
            "timestamp", System.currentTimeMillis()
        );
        
        return ResponseEntity.ok(metrics);
    }

    /**
     * 获取连接详情
     * @return 连接详情
     */
    @GetMapping("/connections")
    public ResponseEntity<Map<String, Object>> getConnections() {
        Map<String, Object> connections = MapUtils.of(
            "total", sseConnectionManager.getActiveConnectionCount(),
            "nodeId", sseConnectionManager.getNodeId(),
            "timestamp", System.currentTimeMillis()
        );
        
        return ResponseEntity.ok(connections);
    }

    /**
     * 健康检查
     * @return 健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> health = MapUtils.of(
            "status", "UP",
            "activeConnections", sseConnectionManager.getActiveConnectionCount(),
            "nodeId", sseConnectionManager.getNodeId(),
            "timestamp", System.currentTimeMillis()
        );
        
        return ResponseEntity.ok(health);
    }
}